#!/usr/bin/env bash

curdir="$(cd "$(dirname $(realpath ${BASH_SOURCE[0]}))"; pwd)"
export SHRC_DIR="$curdir"

pushd "${ZDOTDIR:-$HOME}"

BACKUP_PREFIX=$(date +"%Y-%M-%dT%T%z")

backup_and_link() {
    local tgt="$1"
    local lnk="$2"

    # 如果已经指向目标，直接返回
    if [[ -L "$lnk" ]] && [[ "$(readlink "$lnk")" == "$tgt" ]]; then
        return 0
    fi

    # 不然，文件存在的话，重命名
    if [[ -e "$lnk" ]]; then
        echo "Backing up $lnk to ${BACKUP_PREFIX}$lnk"
        mv "$lnk" "${BACKUP_PREFIX}$lnk"
    fi

    echo "Creating symlink: $lnk -> $tgt"
    ln -sf "$tgt" "$lnk"
}
backup_and_link "${SHRC_DIR}/zlogin.sh"      ".zlogin"
backup_and_link "${SHRC_DIR}/zlogout.sh"     ".zlogout"
backup_and_link "${SHRC_DIR}/zprofile.sh"    ".zprofile"
backup_and_link "${SHRC_DIR}/zshenv.sh"      ".zshenv"
backup_and_link "${SHRC_DIR}/zshrc.sh"       ".zshrc"

popd

if [[ "$PWD" != "$HOME" ]]; then
    pushd $HOME

    # fallback
    backup_and_link "${SHRC_DIR}/zshenv.sh"      ".zshenv"

    popd
fi

TARGET_SHELL=zsh
if [[ "$(basename "$(sh -c "echo \$SHELL")")" == $TARGET_SHELL ]]; then
    echo "Already set $TARGET_SHELL as default shell"
else
    echo "Setting $TARGET_SHELL as user shell"
    chsh -s "$(which $TARGET_SHELL)" $USER
fi
